<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="组件类型" prop="compType">
        <el-select v-model="queryParams.compType" placeholder="请选择" @change="handleQuery" clearable size="small">
          <el-option
            v-for="dict in dict.type.component_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="组件名称" prop="compName">
        <el-input
          v-model="queryParams.compName"
          placeholder="请输入组件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dmpcomponent:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dmpcomponent:config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dmpcomponent:config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dmpcomponent:config:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @row-dblclick="showForm"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" width="55" align="center" prop="compId" />
      <el-table-column label="组件类型" align="center" prop="compType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.component_type" :value="scope.row.compType"/>
        </template>
      </el-table-column>
      <el-table-column label="组件名称" align="center" prop="compName" />
      <el-table-column label="组件描述" align="center" prop="compDesc" />
      <el-table-column label="组件版本" align="center" prop="compVersion" />
      <el-table-column label="组件用途" align="center" prop="compUseto">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.component_useto" :value="scope.row.compUseto ? scope.row.compUseto.split(',') : []"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dmpcomponent:config:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dmpcomponent:config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通用组件配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="组件类型" prop="compType">
          <el-select v-model="form.compType" @change="compTypeChange" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.component_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组件名称" prop="compName">
          <el-input v-model="form.compName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="组件描述" prop="compDesc">
          <el-input v-model="form.compDesc" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="组件版本" prop="compVersion">
          <el-input v-model="form.compVersion" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="组件用途">
          <el-checkbox-group v-model="form.compUseto">
            <el-checkbox
              v-for="dict in dict.type.component_useto"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-divider content-position="center">通用组件配置 键值对参数信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDmpComponentConfigParams">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDmpComponentConfigParams">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="dmpComponentConfigParamsList" :row-class-name="rowDmpComponentConfigParamsIndex" @selection-change="handleDmpComponentConfigParamsSelectionChange" ref="dmpComponentConfigParams">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="配置键" :render-header="tableHeaderAddRedMi" prop="compParamKey">
            <template slot-scope="scope">
              <!--通过变量控制是否显示-->
              <el-select v-if="isShowComponentSpark" v-model="scope.row.compParamKey" placeholder="请选择">
                <!--不同的类型使用相应的字典-->
                <el-option
                  v-for="dict in dict.type.compParamKey_Spark"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="配置键值" :render-header="tableHeaderAddRedMi" prop="compParamVal">
            <template slot-scope="scope">
              <el-input v-model="scope.row.compParamVal" placeholder="请输入" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isShowConfimBtn" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig } from "@/api/dmpcomponent/config";

export default {
  name: "Config",
  dicts: ['component_type', 'component_useto', 'compParamKey_Spark'],
  data() {
    return {
      // 组件类型改变之前的值
      compTypeChangBefore: "",
      // 是否显示组件 Spark 的配置键值对下拉项，默认为false 隐藏
      isShowComponentSpark: false,
      // 是否显示确定/提交按钮,默认true显示
      isShowConfimBtn: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedDmpComponentConfigParams: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通用组件配置表格数据
      configList: [],
      // 通用组件配置键值对参数表格数据
      dmpComponentConfigParamsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        compType: null,
        compName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        compType: [
          { required: true, message: "组件类型不能为空", trigger: "change" }
        ],
        compName: [
          { required: true, message: "组件名称不能为空", trigger: "blur" }
        ],
        compVersion: [
          { required: true, message: "组件版本不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建日期不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 表头添加红色*号
    tableHeaderAddRedMi(cerateElement, {column}) {
      return cerateElement("div", [
        cerateElement("span", column.label),
        cerateElement("span", {
          domProps: {
            innerHTML: "*"
          },
          style: {
            color: "red",
            fontSize: "16px",
            marginLeft: "5px"
          }
        })
      ]);
    },
    /** 查询通用组件配置列表 */
    getList() {
      this.loading = true;
      listConfig(this.queryParams).then(response => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        compId: null,
        compType: null,
        compName: null,
        compDesc: null,
        compVersion: null,
        compUseto: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.dmpComponentConfigParamsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.compId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通用组件信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const compId = row.compId || this.ids
      getConfig(compId).then(response => {
        this.form = response.data;
        this.form.compUseto = this.form.compUseto.split(",");
        this.dmpComponentConfigParamsList = response.data.dmpComponentConfigParamsList;
        this.open = true;
        this.title = "修改通用组件信息";
        this.isShowConfimBtn = true;// 显示确定按钮
        this.showCompTypeSelectOption();
        this.compTypeChangBefore = this.form.compType;
      });
    },
    /** 查看按钮操作 */
    showForm(row) {
      this.reset();
      const compId = row.compId || this.ids
      getConfig(compId).then(response => {
        this.form = response.data;
        this.form.compUseto = this.form.compUseto.split(",");
        this.dmpComponentConfigParamsList = response.data.dmpComponentConfigParamsList;
        this.open = true;
        this.title = "查看通用组件信息";
        this.isShowConfimBtn = false;// 隐藏确定按钮
        this.showCompTypeSelectOption();
        this.compTypeChangBefore = this.form.compType;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // ---------------------------------------- 子表填写内容进行检验 ----------------------------------------
          var compParamsListLen = this.dmpComponentConfigParamsList.length
          for (var i = 0; i < compParamsListLen; i++) {
            var compParamKeyStr = this.dmpComponentConfigParamsList[i].compParamKey.trim();
            var compParamValStr = this.dmpComponentConfigParamsList[i].compParamVal.trim();

            if (compParamKeyStr.length == 0 || compParamValStr.length == 0) {
              this.$alert('键值对参数信息 有必填项未填写，请核对!!', '提示', {
                type: "error",
                onfirmButtonText: '确定'
              });
              return;
            }
          }

          this.form.compUseto = this.form.compUseto.join(",");
          this.form.dmpComponentConfigParamsList = this.dmpComponentConfigParamsList;

          if (this.form.compId != null) {
            updateConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const compIds = row.compId || this.ids;
      this.$modal.confirm('是否确认删除通用组件配置编号为"' + compIds + '"的数据项？').then(function() {
        return delConfig(compIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 通用组件配置键值对参数序号 */
    rowDmpComponentConfigParamsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 通用组件配置键值对参数添加按钮操作 */
    handleAddDmpComponentConfigParams() {
      if(!this.form.compType){
        this.$modal.msgError("请先选择 组件类型 !!");
        return;
      }
      let obj = {};
      obj.compParamKey = "";
      obj.compParamVal = "";
      this.dmpComponentConfigParamsList.push(obj);
    },
    /** 通用组件配置键值对参数删除按钮操作 */
    handleDeleteDmpComponentConfigParams() {
      if (this.checkedDmpComponentConfigParams.length == 0) {
        this.$modal.msgError("请先选择要删除的通用组件配置键值对参数数据");
      } else {
        const dmpComponentConfigParamsList = this.dmpComponentConfigParamsList;
        const checkedDmpComponentConfigParams = this.checkedDmpComponentConfigParams;
        this.dmpComponentConfigParamsList = dmpComponentConfigParamsList.filter(function(item) {
          return checkedDmpComponentConfigParams.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleDmpComponentConfigParamsSelectionChange(selection) {
      this.checkedDmpComponentConfigParams = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dmpcomponent/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    // 根据compType的内容决定显示哪个组件的配置键值下拉项
    showCompTypeSelectOption() {
      // 一. 配置键值下拉项都先隐藏掉
      this.isShowComponentSpark = false;
      // 二. 根据选择进行处理
      if ("Spark" == this.form.compType) {
        // 1. 显示所选组件的配置键下拉项
        this.isShowComponentSpark = true;
        // 2, 隐藏其它采集引擎的配置键下拉项
      }
    },
    /** 组件类型下拉项改变事件*/
    compTypeChange(val) {
      // 1. 控制显示隐藏
      this.showCompTypeSelectOption();

      // 2. 清空键值对参数前提醒
      var componentParamsListLen = this.dmpComponentConfigParamsList.length;
      if (componentParamsListLen > 0) {
        this.$confirm('类型改变，将删除已配置的键值对参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 清空键值对参数
          this.dmpComponentConfigParamsList = [];

        }).catch(() => {
          // 点击了取消
          // 将下拉项恢复到改变之前
          this.form.compType = this.compTypeChangBefore
        });
      }
    },




  }
};
</script>
